<?php
namespace gnomephp\captcha;

class Captcha{
	
	/**
	 * The session name.
	 * @var string
	 */
	const SESSION_NAME = 'gnomephp.captchaResponse';
	
	// This is just a pre-salt, see getSalt() 
	const SALT = '¤"!(#"!CSA____-__dj2319¤"/("""#"!%';
	
	const CAPTCHA_POST_NAME = 'captcha_verification';
	
	/**
	 * 
	 * @var gnomephp\Session
	 */
	protected $session;
	
	/**
	 * @var gnomephp\input\Input
	 */
	protected $input;
	
	
	public function __construct($session, $input){
		$this->session = $session;
		$this->input = $input;
	}
	
	
	/**
	 * Checks if the captcha by name is valid. optional value if input name is changed and forexample not using post to validate this captcha.
	 * 
	 * Note that if no name is set, default name will be used wich refers to \gnomephp\captcha\Captcha::CAPTCHA_POST_NAME
	 * 
	 * @param string name The name of the captcha to check. Every captcha on a page should have a unique captcha, this means that multiple captchas is supported in one page load.
	 * @param string $value If this is not set, default value from POST will be get.
	 */
	public function isVerified($name=null, $value = null){
		if ($name===null){
			$name = \gnomephp\captcha\Captcha::CAPTCHA_POST_NAME;
		}
		
		// Get default name.
		if ($value === null && $this->input->post){
			$value = $this->input->post->get($name);
		}
		$session = $this->session->get(Captcha::getSessionName($name));
		
		$this->session->delete(Captcha::getSessionName($name));
		$this->session->save();

		if (!$value || !$session)return false;
		
		if($session == Captcha::getValue(strtoupper($value)))return true;
		
		return false;
	}
	
	static public function getValue($val){
		return sha1(self::getSalt() . $val);
	}
	
	static public function getSessionName($name){
		return sha1(self::CAPTCHA_POST_NAME . $name );
	}
	
	
	/**
	 * Generate unique salt based on application name.
	 */
	static public function getSalt(){
		self::SALT . GNOME_APP_NS;
	}
	
	
	
}